<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>云盘首页</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #4a90e2;
            color: white;
            padding: 10px 20px;
            text-align: center;
        }
        .nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #333;
            padding: 10px 20px;
        }
        .nav a {
            color: white;
            text-decoration: none;
            margin: 0 10px;
        }
        .user-info {
            color: white;
            margin-left: auto;
        }
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .file-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .file-list li {
            padding: 10px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .file-list li:last-child {
            border-bottom: none;
        }
        .upload-button {
            background-color: #4a90e2;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .upload-button:hover {
            background-color: #3a79c2;
        }
        .file-info {
            margin-top: 10px;
            font-size: 14px;
            color: #555;
        }
        .file-actions {
            display: flex;
            gap: 10px;
        }
        .file-actions button {
            background-color: #e74c3c;
            color: white;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            border-radius: 5px;
        }
        .file-actions button.download {
            background-color: #2ecc71;
        }
        .file-actions button:hover {
            background-color: #c0392b;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>云盘首页</h1>
    </div>
    <div class="nav">
        <a href="#">首页</a>
        <a href="#">文件管理</a>
        <a href="#">分享</a>
        <a href="#">设置</a>
        <a href="#">退出</a>
        <div class="user-info" id="user-info">加载中...</div>
    </div>
    <div class="container">
        <!-- 文件选择和上传按钮 -->
        <input type="file" id="file-input" style="display: none;" onchange="updateFileInfo();"> <!-- 隐藏的文件输入框 -->
        <button class="upload-button" onclick="document.getElementById('file-input').click();">请选择你要上传的文件</button>

        <!-- 显示文件选择信息 -->
        <div class="file-info" id="file-info" style="display: none;">
            <span id="selected-file-name">无文件选择</span>
        </div>

        <!-- 上传按钮 -->
        <button class="upload-button" onclick="uploadFile()">上传文件</button> 
        <!-- <button class="upload-button" id="upload-button" onclick="uploadFile()" disabled>上传文件</button> 初始状态禁用按钮 -->

        <ul class="file-list" id="file-list">
            <li class="header-row">
                <span>文件名</span>
                <span>大小</span>
                <span>修改日期</span>
                <span>操作</span>
            </li>
            <!-- 更多文件项 -->
        </ul>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    <script>
        // 更新文件选择信息
        function updateFileInfo() {
            const fileInput = document.getElementById('file-input');
            const fileName = fileInput.files[0] ? fileInput.files[0].name : '无文件选择';
            const fileInfo = document.getElementById('file-info');
            const selectedFileName = document.getElementById('selected-file-name');

            selectedFileName.innerText = fileName;
            fileInfo.style.display = fileName !== '无文件选择' ? 'block' : 'none';

            // 更新上传按钮的文本
            const uploadButton = document.querySelectorAll('.upload-button')[1];
            if (fileName !== '无文件选择') {
                uploadButton.innerText = '开始上传';
            } else {
                uploadButton.innerText = '上传文件';
            }
        }
        async function fetchUserInfo() {
            try {
                const username = localStorage.getItem('username');
                const token = localStorage.getItem('token');

                if (!username || !token) {
                    throw new Error('缺少用户名或令牌');
                }

                const formData = new FormData();
                formData.append('username', username);
                formData.append('token', token);

                const response = await fetch('/user/info', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('网络响应错误: ' + response.statusText);
                }

                const data = await response.json();
                document.getElementById('user-info').innerText = `用户: ${data.data.Username} | 注册日期: ${data.data.SignupAt}`;
            } catch (error) {
                console.error('获取用户信息时出现问题:', error);
                document.getElementById('user-info').innerText = '获取用户信息失败';
            }
        }

        // 加载用户文件列表
        async function loadFileList() {
            const username = localStorage.getItem('username');
            const token = localStorage.getItem('token');
            const limit = 20; // 设置查询的文件数量限制

            if (!username || !token) {
                alert('未登录或令牌失效！');
                return;
            }

            try {
                const response = await fetch(`/file/meta?username=${username}&limit=${limit}`);
                if (!response.ok) {
                    throw new Error('无法加载文件信息');
                }

                const userFiles = await response.json();

                // 清空当前文件列表
                // const fileList = document.getElementById('file-list');
                // fileList.innerHTML = '';  // 清空列表

                renderFileList(userFiles);
            } catch (error) {
                console.error('获取文件列表失败:', error);
                alert('获取文件列表失败');
            }
        }
        // 存储已经显示的文件的 sha1
        let displayedFiles = new Set();

        // 计算文件的 SHA1 哈希值
        function calculateFileHash(file) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const arrayBuffer = e.target.result;
                    const wordArray = CryptoJS.lib.WordArray.create(new Uint8Array(arrayBuffer));
                    const hash = CryptoJS.SHA1(wordArray).toString(CryptoJS.enc.Hex);
                    resolve(hash);
                };
                reader.onerror = function(error) {
                    reject('文件哈希计算失败');
                };
                reader.readAsArrayBuffer(file);
            });
        }
        
        // 渲染文件列表
        function renderFileList(files) {
            const fileList = document.getElementById('file-list');
            if (!fileList) {
                console.error('file-list 元素不存在');
                return;
            }

             // 获取表头行
             const headerRow = fileList.querySelector('.header-row');

             // 先清空文件列表中的内容（去除除了表头外的部分）
            while (fileList.children.length > 1) {
                fileList.removeChild(fileList.lastChild);
            }

            // 清空文件列表，只清空一次
            //fileList.innerHTML = '';

            // 清空文件列表，但保留表头
            // while (fileList.firstChild) {
            //     if (fileList.firstChild !== headerRow) {
            //         fileList.removeChild(fileList.firstChild);
            //     } else {
            //         break;
            //     }
            // }

            // 遍历文件列表并添加到页面
            files.forEach(file => {
                // 如果文件已经显示过，跳过它
                // if (displayedFiles.has(file.FileSha1)) {
                //     return;
                // }

                const fileItem = document.createElement('li');
                fileItem.innerHTML = `
                    <span>${file.FileName}</span>
                    <span>${formatFileSize(file.FileSize)}</span>
                    <span>${file.UploadAt}</span>
                    <span class="file-actions">
                        <button class="download" onclick="downloadFile('${file.FileSha1}')">下载</button>
                        <button class="delete" onclick="deleteFile('${file.FileSha1}')">删除</button>
                    </span>
                `;
                fileList.appendChild(fileItem);

                // 将文件的 sha1 添加到集合中
                displayedFiles.add(file.FileSha1);
            });
        }

        // 格式化文件大小
        function formatFileSize(size) {
            if (size < 1024) return `${size} B`;
            else if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
            else if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
            else return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
        }

        // 删除文件
        async function deleteFile(fileSha1) {
            const username = localStorage.getItem('username');
            const token = localStorage.getItem('token');
            if (!username || !token) {
                alert('未登录或令牌失效！');
                return;
            }

            try {
                const response = await fetch(`/file/delete?username=${username}&fileSha1=${fileSha1}`, {
                    method: 'DELETE'
                });
                if (!response.ok) {
                    throw new Error('文件删除失败');
                }

                alert('文件删除成功');
                loadFileList(); // 删除后重新加载文件列表
            } catch (error) {
                console.error('删除文件失败:', error);
                alert('删除文件失败');
            }
        }

        // 下载文件
        function downloadFile(fileSha1) {
            const username = localStorage.getItem('username');
            const token = localStorage.getItem('token');
            if (!username || !token) {
                alert('未登录或令牌失效！');
                return;
            }

            // 跳转到文件下载接口
            window.location.href = `/file/download?username=${username}&fileSha1=${fileSha1}`;
        }


        // 上传文件
        async function uploadFile() {
            const fileInput = document.getElementById('file-input');
            const file = fileInput.files[0];
            if (!file) {
                alert('请选择文件！');
                return;
            }

            try {
                const username = localStorage.getItem('username');
                const token = localStorage.getItem('token');
                if (!username || !token) {
                    alert('未登录或令牌失效！');
                    return;
                }

                // const filehash = await calculateFileHash(file);
                // const filesize = file.size;
                // const filename = file.name;

                const formData = new FormData();
                formData.append('file', file);
                formData.append('username', username);
                formData.append('token', token);
                // formData.append('username', username); // 用户名
                // formData.append('filehash', filehash); // 文件哈希值
                // formData.append('filename', filename); // 文件名
                // formData.append('filesize', filesize); // 文件大小

                const response = await fetch('/file/upload', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('文件上传失败');
                }

                const result = await response.text(); // 这里假设返回的是文本
                alert(result); // 显示上传结果
                // const result = await response.json();

                // // 根据后端返回的消息做相应处理
                // if (result.Code === 0) {
                //     alert(result.Msg); // 秒传成功
                // } else {
                //     alert(result.Msg); // 秒传失败
                // }

                // 上传完成后，重置选择文件和按钮状态
                resetUploadState();

                // 上传完成后查询文件信息
                loadFileList();
            } catch (error) {
                console.error('上传失败:', error);
                alert('上传失败');
            }
        }
        

        // 重置上传状态
        function resetUploadState() {
            const fileInput = document.getElementById('file-input');
            const uploadButton = document.querySelectorAll('.upload-button')[1];
            const fileInfo = document.getElementById('file-info');
            const selectedFileName = document.getElementById('selected-file-name');

            // 清空文件选择框
            fileInput.value = '';

            // 隐藏文件信息
            selectedFileName.innerText = '无文件选择';
            fileInfo.style.display = 'none';

            // 更新按钮文本
            //uploadButton.innerText = '请选择你要上传的文件';
        }

        window.onload = function() {
            // 页面加载时获取用户信息
            fetchUserInfo();

            // 页面加载时获取文件列表
            loadFileList();

            const fileInfo = document.getElementById('file-info');
            fileInfo.style.display = 'none'; // 页面加载时隐藏文件信息
        }
    
    </script>
</body>
</html>